<template>
  <Tabs :value="tab.value" @on-click="tabClick">
    <!--class="container"-->
    <Tab-pane label="角色列表" name="list">
      <div class="tool-wrap">
        <Button-group class="rf">
          <i-button type="ghost" icon="plus" class="tool-btn" @click="showModalDialog()">增加角色</i-button>
          <i-button type="ghost" icon="trash-a" class="tool-btn" @click="deleteRoleList()">批量删除角色</i-button>
        </Button-group>
      </div>
      <i-table :columns="columns" :data="roleList" @on-selection-change="selectionChange" >
      </i-table>
    </Tab-pane>
    <Tab-pane label="角色用户" name="roleUser">
      <div class="tool-wrap">
        <Button-group class="rf">
          <i-button type="ghost" icon="plus" class="tool-btn" @click="showRoleUserModal()">添加用户</i-button>
          <i-button type="ghost" icon="plus" class="tool-btn" @click="deleteRoleUser()">删除用户</i-button>
        </Button-group>
      </div>
      <Row :gutter="10">
        <i-col span="6">
        <i-table highlight-row :columns="[{title: '角色', key: 'name'}]" :data="roleList"
                 @on-current-change="currentChange">
        </i-table>
        </i-col>
        <i-col span="18">
        <i-table
          :columns="[{type: 'selection', width: 62, align: 'center'},{title: '用户', key: 'name'},{title: '电话', key: 'telephone'},{title: 'QQ', key: 'qq'}]"
          :data="roleUser.has"
          @on-selection-change="selectRoleHasUser">
        </i-table>
        </i-col>
      </Row>
    </Tab-pane>
    <Modal v-model="roleModal.show"
           :title="roleModal.title"
           :loading="roleModal.loading"
           @on-ok="saveRole"
           ok-text="保存"
           cancel-text="关闭">
      <i-form :ref="roleModal.formName" :model="roleModal.formData" :rules="roleModal.rules" :label-width="80">
        <Form-item label="角色名" prop="name">
          <i-input v-model="roleModal.formData.name" placeholder="输入角色名"/>
        </Form-item>
        <Form-item label="角色描述" prop="describe">
          <i-input v-model="roleModal.formData.describe" placeholder="请输入角色描述"/>
        </Form-item>
      </i-form>
    </Modal>
    <Modal
      v-model="roleUserModal.show"
      :title="roleUserModalTitle"
      @on-ok="saveRoleUser"
      ok-text="保存"
      cancel-text="关闭">
      <i-table
        :columns="[{type: 'selection', width: 62, align: 'center'}, {title: '用户', key: 'name'}]"
        :data="roleUser.not"
        @on-selection-change="selectRoleNotUser">
      </i-table>
    </Modal>
  </Tabs>
</template>
<script>
  import roleApi from '../../../api/admin/role'
  import {isConfirm} from '../../../assets/admin/js/common'

  let emptyRoleForm = {
    id: 0,
    name: '',
    describe: '',
    menu_list: ''
  }

  export default{
    components: {},
    data () {
      return {
        tab: {
          value: 'list'
        },
        roleModal: {
          show: false,
          formName: 'roleForm',
          formData: {...emptyRoleForm},
          title: '新增角色',
          loading: false,
          rules: {
            name: [
              {type: 'string', required: true, message: '请填写角色名', trigger: 'blur'}
            ],
            describe: [
              {type: 'string', message: '请填写描述', trigger: 'blur'}
            ]
          }
        },
        roleUserModal: {
          show: false,
          loading: false,
          userIds: []
        },
        columns: [
          {
            type: 'selection',
            width: 62,
            align: 'center'
          },
          {
            title: '角色名',
            key: 'name'
          },
          {
            title: '角色说明',
            key: 'describe'
          },
          {
            title: '创建时间',
            key: 'updated_at'
          },
          {
            title: '更新时间',
            key: 'updated_at'
          },
          {
            title: '操作',
            className: 'option-column',
            render: (h, params) => {
              let self = this
              return h('div', [
                h('Tooltip', {
                  props: {
                    content: '编辑',
                    placement: 'top'
                  }
                }, [
                  h('Button', {
                    props: {
                      type: 'text',
                      icon: 'edit'
                    },
                    on: {
                      click: () => {
                        self.showModalDialog(params.row)
                      }
                    }
                  })
                ]),
                h('Tooltip', {
                  props: {
                    content: '删除',
                    placement: 'top'
                  }
                }, [
                  h('Button', {
                    props: {
                      type: 'text',
                      icon: 'trash-a'
                    },
                    on: {
                      click: () => {
                        self.deleteRole(params.row)
                      }
                    }
                  })
                ]),
                h('Tooltip', {
                  props: {
                    content: '添加用户',
                    placement: 'top'
                  }
                }, [
                  h('Button', {
                    props: {
                      type: 'text',
                      icon: 'person-add'
                    },
                    on: {
                      click: () => {
                        self.selectRole['_highlight'] = false
                        self.selectRole = self.roleList[params.index]
                        self.selectRole['_highlight'] = true
                        self.getRoleUser()
                        self.tab.value = 'roleUser'
                      }
                    }
                  })
                ])
              ])
            }
          }
        ],
        roleList: [],
        selectRoleList: [],
        selectRole: {},
        selectUserIds: [],
        roleUser: {
          has: [],
          not: []
        }
      }
    },
    computed: {
      roleUserModalTitle () {
        return `给【${this.selectRole.name}】增加用户`
      }
    },
    methods: {
      tabClick (name) {
        let self = this
        if (name === 'roleUser') {
          if (!(self.selectRole.hasOwnProperty('id'))) {
            self.selectRole = self.roleList[0]
            self.selectRole['_highlight'] = true
          }
          this.getRoleUser()
        }
      },
      selectionChange (selections) {
        this.selectRoleList = selections
      },
      currentChange (currentRow) {
        this.selectRole = currentRow
        this.getRoleUser()
      },
      showModalDialog (role) {
        this.roleModal.formData = {...emptyRoleForm}
        if (role) {
          this.roleModal.title = '编辑用户'
          this.roleModal.formData = {...role}
        }
        this.roleModal.show = true
      },
      showRoleUserModal () {
        this.roleUserModal.show = true
      },
      selectRoleHasUser (selection) {
        let self = this
        self.selectUserIds = []
        selection.forEach(user => {
          self.selectUserIds.push(user.id)
        })
      },
      selectRoleNotUser (selection) {
        let self = this
        self.roleUserModal.userIds = []
        selection.forEach(user => {
          self.roleUserModal.userIds.push(user.id)
        })
      },
      getRoleList () {
        let self = this
        roleApi.getRoleList(data => {
          data.forEach(role => {
            role['_highlight'] = false
          })
          self.roleList = data
        })
      },
      saveRole () {
        let self = this
        self.$refs[self.roleModal.formName].validate((valid) => {
          if (!valid) {
            return
          }
          roleApi.saveRole(self.roleModal.formData, () => {
            self.getRoleList()
            self.roleModal.show = false
            self.$Message.success('角色保存成功')
          }, (msg) => {
            self.roleModal.loading = false
            self.$Message.warning(msg)
          })
        })
      },
      deleteRole (row) {
        let self = this
        isConfirm(`删除角色【${row.name}】？`, () => {
          roleApi.deleteRole(row.id, () => {
            self.$Message.success(`删除角色【${row.name}】成功！`)
            self.getRoleList()
          })
        })
      },
      deleteRoleList () {
        const self = this
        const selectRoleList = self.selectRoleList
        const ids = []
        let names = []
        if (selectRoleList.length === 0) {
          self.$Message.warning('请选择角色')
          return
        }
        selectRoleList.forEach(item => {
          ids.push(item.id)
          names.push(item.name)
        })
        names = names.join(',')
        isConfirm(`删除角色【${names}】？`, () => {
          roleApi.deleteRoleList({ids: ids}, () => {
            self.$Message.success(`删除角色【${names}】成功！`)
            self.selectRoleList = []
            self.getRoleList()
          })
        })
      },
      getRoleUser () {
        let self = this
        roleApi.getRoleUser(self.selectRole.id || 0, data => {
          self.roleUser = data
        })
      },
      saveRoleUser () {
        let self = this
        roleApi.saveRoleUser(self.selectRole.id, self.roleUserModal.userIds, () => {
          self.getRoleUser()
        })
      },
      deleteRoleUser () {
        let self = this
        roleApi.deleteRoleUser(self.selectRole.id, self.selectUserIds, () => {
          self.getRoleUser()
        })
      }
    },
    created () {
      this.getRoleList()
    }
  }
</script>
<style lang="less">
  .roleMenu {
    height: 100%;
  }
</style>
